<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>学员学习情况管理</span>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline>

      <el-form-item label="培训计划">
        <el-select v-model="user.trainingPlanId" placeholder="请选择培训计划" style="width: 200px">
          <el-option v-for="item in trainingPlanList" :key="item.value" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="姓名">
        <el-input v-model="user.name" placeholder="请输入姓名" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="所属机构">
        <el-select v-model="user.agencyId" placeholder="请选择所属机构" style="width: 340px">
          <el-option v-for="item in agencyList" :key="item.value" :label="item.name" :value="item.id" />
        </el-select>
        <el-button type="primary" @click="show" style="margin-left: 15px;">查询</el-button>
        <el-button  @click="clear">重置</el-button>
        <el-button type="primary" @click="exportData">导出</el-button>
      </el-form-item>


    </el-form>




    <el-form>
      <el-row>
        <el-col :span="7">
          <el-form-item label="平均分/总分">{{ avgScore }}/{{ allScore }}</el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="及格人数/总人数">{{ passNum }}/{{ unPassNum }}</el-form-item>
        </el-col>、
        <el-col :span="7">
          <el-form-item label="及格率">{{ rateOfPass }}</el-form-item>
        </el-col>、
      </el-row>

    </el-form>


    <el-table ref="multipleTable" :data="tableData" style=" width: 100%;">
      <el-table-column prop="id" label="编号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="name" label="姓名" header-align="center" align="center"></el-table-column>
      <el-table-column prop="agencyId" label="归属机构" header-align="center" align="center">
        <template slot-scope="scope">
          {{ getAgencyName(scope.row.agencyId) }}
        </template>
      </el-table-column>

      <el-table-column prop="score" label="成绩" header-align="center" align="center"></el-table-column>
      <template #empty>
      <el-empty description="没有数据" />
    </template>
    </el-table>



  </el-card>





</template>
<script>


import { addUser, changeUser, deleteUser, getAllUsers } from "@/api/user";
import { getAgencyList } from "@/api/agency";
import { getTrainingPlanList } from "@/api/trainingPlan";
import { getLearningSituationOfOnePlan } from "@/api/learningSituation";
import { getDocumentVideoList } from "@/api/documentVideo";
import { getExamSituationList, getExamSituationOfOnePlan } from "@/api/Score";
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 表格数据
      tableData: [],
      addOrUpdate: true,//true为add
      user: {},
      form: {},
      posts: [],
      multipleSelection: [],
      selectedIds: [],
      agencyList: [],
      formLabelWidth: "80px",
      theMajorOfMy: "",
      trainingPlanList: [],
      userSituation: [],
      documentVideoList: [],

      loading: false,
      //统计分析
      rateOfPass: 0,//及格率
      avgScore: 0,//均分
      allScore: 0,//总分
      passNum: 0,//及格人数
      unPassNum: 0,//总人数


    }
  },
  methods: {

    show() {
      this.passNum = 0;

      getExamSituationOfOnePlan(this.user, this.currentPage, this.pageSize).then((res) => {
        // console.log(res)
        if (res.data.code === 1) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;
          if (this.tableData.length === 0 && this.currentPage > 1) {
            this.currentPage -= 1;
            this.show()
          }
          console.log(this.tableData)

          this.unPassNum = this.tableData.length; // 总人数
          let totalScore = 0; // 总分
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].score !== null) {
              let scores = parseInt(this.tableData[i].score.split('/')[0], '10');
              let allScore = parseInt(this.tableData[i].score.split('/')[1], '10');
              this.allScore = allScore;
              if (scores >= allScore * 0.6) {
                this.passNum += 1;
              }
              totalScore += scores;
            }
          }
          // 计算均分
          this.avgScore = totalScore / this.tableData.length;
          // 计算及格率
          this.rateOfPass = this.passNum / this.tableData.length;

        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {

      })
    },
    clear() {
      this.tableData = [];
      this.user = {};
      this.avgScore = 0;
      this.allScore = 0;
      this.passNum = 0;
      this.unPassNum = 0;
      this.rateOfPass = 0;

      
    },
    add() {
      this.user = {};
      this.user.password = "1234567";
      this.addOrUpdate = true;
      this.dialogVisible = true;
    },
    addForm() {

      if (this.addOrUpdate) {
        addUser(this.user).then(res => {
          if (res.data.code === 1) {
            this.$message.success("保存成功")
            this.dialogVisible = false;
            this.show();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
        });
      } else {
        changeUser(this.user).then(res => {
          console.log(res)
          if (res.data.code === 1) {
            this.$message.success("更新成功")
            this.dialogVisible = false;
            this.user.status = "正常";
            this.show();
          }
        }).catch(e => {
        });
      }

    },

    close() {
      this.dialogVisible = false;
      this.user = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateInfo(id) {
      this.addOrUpdate = false;
      this.userSituation = this.tableData.filter(data => data.id == id)[0].learningSituation;
      this.dialogVisible = true;
    },

    getAllAgencyList() {
      getAgencyList().then((res) => {
        if (res.data.code === 1) {
          this.agencyList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getAgencyName(id) {
      let agency = this.agencyList.find(data => data.id === id);
      return agency ? agency.name : "";
    },
    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.show();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.show();
    },

    getTrainingsPlanList() {
      getTrainingPlanList().then((res) => {
        if (res.data.code === 1) {
          this.trainingPlanList = res.data.data;
        } else {
          console.log(res.data.msg);
        }
      }).catch((e) => {
      })
    },

    getDocumentVideoName(id) {
      const types = this.documentVideoList.find(t => t.id === id);
      return types ? types.name : '';
    },
    getDocumentVideoLists() {
      getDocumentVideoList().then((res) => {
        if (res.data.code === 1) {
          this.documentVideoList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getTrainingPlanName(id) {
      const types = this.trainingPlanList.find(t => t.id === id);
      return types ? types.name : '';
    },


    //数据导出
    async exportData() {

      this.loading = true;
      this.currentPage = 1;
      this.pageSize = this.totalCount;


      try {
        await getExamSituationList(this.user).then((res) => {
          if (res.data.code === 1) {
            this.tableData = res.data.data;
            //将learningSituationList拆开放入属性中
            const data = this.tableData;

            // 创建工作簿对象
            const wb = XLSX.utils.book_new();

            // 将数据添加到工作簿中，假设 data 是一个二维数组或对象数组
            // 如果 data 是对象数组，使用 XLSX.utils.json_to_sheet(data)
            // 如果 data 是二维数组，使用 XLSX.utils.aoa_to_sheet(data)
            const ws = XLSX.utils.json_to_sheet(data);

            // 将工作表添加到工作簿中
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
            // 写入工作簿，生成 XLSX 文件
            const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
            // 使用 FileSaver 保存文件
            try {
              FileSaver.saveAs(
                new Blob([wbout], { type: "application/octet-stream" }),
                this.getTrainingPlanName(this.user.trainingPlanId) + "_考试成绩.xlsx"
              );
            } catch (e) {
              console.error(e);
            }

          }
        }).catch((e) => { })
      } finally {
        this.currentPage = 1;
        this.pageSize = 5;
        this.show();
        this.loading = false;
      }
    },


  },
  mounted() {
    this.getAllAgencyList();
    this.getTrainingsPlanList();
    this.getDocumentVideoLists();
  },
};
</script>


<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}


.basic-info-container {
  display: flex; // 使用flex布局
  flex-wrap: wrap; // 允许元素换行
  margin-right: -10px; // 调整外边距以对齐
}

.basic-info-border,
.basic-info-border2 {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  position: relative;
  padding-top: 30px;
  margin-bottom: 20px; // 添加底部外边距
  width: 100%; // 设置宽度为100%，或者您可以设置一个固定的宽度
  box-sizing: border-box; // 确保padding和border包含在宽度内
}

.basic-info-border::before,
.basic-info-border2::before {
  content: "";
  position: absolute;
  top: -15px;
  left: 10px;
  background-color: #409EFF;
  color: white;
  padding: 5px;
  border-radius: 3px;
  font-weight: bold;
}

.basic-info-border::before {
  content: "基本信息";
}

.basic-info-border2::before {
  content: "客户关键人物信息";
}

// 如果需要，可以为两个框设置最大宽度
.max-width-box {
  max-width: 900px; // 或者您希望的任何宽度
}
</style>
<script setup>
</script>
